package com.yrot.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yrot.admin.dto.RelatedStaff;
import com.yrot.admin.dto.TrainInfo;
import com.yrot.admin.entity.SysResult;
import com.yrot.admin.entity.SysTrain;
import com.yrot.admin.entity.SysUsers;
import com.yrot.admin.form.ResultAccuracyJson;
import com.yrot.admin.mapper.SysResultMapper;
import com.yrot.admin.mapper.SysTrainMapper;
import com.yrot.admin.mapper.SysUsersMapper;
import com.yrot.admin.service.ISysResultService;
import com.yrot.admin.service.ISysTrainService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yrot.admin.service.ISysUsersService;
import com.yrot.common.properties.StaticProperties;
import com.yrot.common.result.R;
import com.yrot.common.utils.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hemin
 * @since 2019-04-02
 */
@Service
@Transactional
@Slf4j
public class SysTrainServiceImpl extends ServiceImpl<SysTrainMapper, SysTrain> implements ISysTrainService {

    @Autowired
    StaticProperties staticProperties;

    @Autowired
    SysResultMapper sysResultMapper;

    @Autowired
    ISysResultService resultService;

    @Autowired
    ISysUsersService usersService;


    @Override
    public R saveTrain(SysTrain sysTrain) {
        try {
            //0.验证名称是否存在
            QueryWrapper<SysTrain> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("train_content",sysTrain.getTrainContent());
            queryWrapper.eq("expert_id",sysTrain.getExpertId());
            if(!list(queryWrapper).isEmpty()){
                return R.error("培训名称已经存在");
            }
            //1.初始化状态
            sysTrain.setTrainStatus(0);
            //新增
            save(sysTrain);
            //2.拼接访问链接
            sysTrain.setTrainUrl(staticProperties.getVisitPath()+"mp/train/exam?tranId="+sysTrain.getTrainId());
            //3.生成二维码图片
            String encode = QRCodeUtil.encode(sysTrain.getTrainUrl(), staticProperties.getStaticLocalPath());
            //4.保存二维码图片地址
            sysTrain.setTrainImg(staticProperties.getStaticVisitPath()+encode);
            saveOrUpdate(sysTrain);
            return R.ok();
        }catch (Exception e){
            log.error("发布培训失败",e);
            return R.error("发布培训失败");
        }
    }

    @Override
    public R findAccuracyByExpertId(Integer ExpertId) {
        QueryWrapper<SysTrain> trainQueryWrapper = new QueryWrapper<>();
        trainQueryWrapper.eq("expert_id", ExpertId);
        List<SysTrain> list = list(trainQueryWrapper);
        if(list.isEmpty()){
            return R.error();
        }
        HashMap<String, Object> map = new HashMap<>();
        ArrayList<Object> time = new ArrayList<>();
        ArrayList<Object> num = new ArrayList<>();
        list.forEach(train->{
            Integer trainId = train.getTrainId();
            ResultAccuracyJson accuracyJson = sysResultMapper.findAccuracyByTrainId(trainId);
            time.add(train.getCreateTime());
            num.add(accuracyJson.getAccuracy());
        });
        map.put("time",time);
        map.put("num",num);
        return R.ok(map);
    }

    @Override
    @Transactional
    public R creatExamAndPeople(TrainInfo trainInfo) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startTime = LocalDateTime.parse(trainInfo.getTrainStart(),df);//考试开始时间
        LocalDateTime endTime = LocalDateTime.parse(trainInfo.getTrainEnd(),df);//考试结束时间
        SysTrain sysTrain = new SysTrain();
        BeanUtils.copyProperties(trainInfo,sysTrain);
        sysTrain.setTrainStart(startTime);
        sysTrain.setTrainEnd(endTime);
        sysTrain.setTrainStatus(0);
        saveOrUpdate(sysTrain);
        Integer trainId = sysTrain.getTrainId();//获取考试id
        if(trainId >0 ){//创建考试成功
            List<RelatedStaff> relatedStaffs = trainInfo.getRelatedStaffs();
            //循环外协人员list，人员信息、人员对应考试:添加到考试结果表
            for (RelatedStaff rs:relatedStaffs) {
                SysResult sysResult = new SysResult();//考试结果
                sysResult.setTrainId(trainId);
                sysResult.setResultCount(trainInfo.getTrainNum().toString());
                sysResult.setRelatedstaffId(rs.getRelatedstaffId());
                //*sysResult.setRelatedstaffBatchId(rs.getRelatedstaffBatchId());
                sysResult.setIdentifier(rs.getIdentifier());
                sysResult.setUserName(rs.getUserName());
                resultService.saveOrUpdate(sysResult);
            }
            return R.ok(trainId);
        }else{
            return R.error("创建考试失败");
        }
    }

}
